package me.monster.smarttraffic.net;

import com.jeremy.retrofitmock.MockInterceptor;

import me.monster.smarttraffic.BuildConfig;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RequestManager {

    private static final String DEBUG_BASE_URL = "https://127.0.0.1/";
    private static final String RELEASE_BASE_URL = "https://127.0.0.1/";

    private Retrofit retrofit;

    private RequestManager() {
    }

    public static RequestManager getInstance() {
        return SingletonInstance.INSTANCE;
    }

    public Api getService() {
        return getRetrofit().create(Api.class);
    }

    private Retrofit getRetrofit() {
        if (retrofit == null) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(new LogInterceptor())
                    .addInterceptor(httpLoggingInterceptor)
                    .addInterceptor(new MockInterceptor())
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(getBaseUrl())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(okHttpClient)
                    .build();
        }
        return retrofit;
    }

    private String getBaseUrl() {
        return BuildConfig.DEBUG ? DEBUG_BASE_URL : RELEASE_BASE_URL;
    }

    private static class SingletonInstance {
        private static final RequestManager INSTANCE = new RequestManager();
    }
}